<template>
  <el-dialog :visible.sync="dialogFormVisible" :before-close="handleClose" class="medium-common-dialog-size">
    <div style="display: flex;align-items: center;">
      <div>
        <Title title="选择需要导出的字段" />
      </div>
      <div v-if="!exportParams.idList || exportParams.idList.length === 0 " style="color: red;font-size: 12px;margin-left: 10px;">单次最多导出5000条</div>
    </div>

    <div v-loading="exportLoading" class="export-excel-mask-select-box check-grounp-style">
      <el-scrollbar class="scroll-container">
        <div class="select-item">
          <div class="select-item-parent select-item-common">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          </div>
        </div>
        <el-checkbox-group v-model="selectKeyword">
          <div v-for="(item, itemIndex) in commonData" :key="itemIndex" class="select-item">
            <div class="select-item-parent select-item-common">
              <el-checkbox
                :indeterminate="item.childIsIndeterminate"
                v-model="item.childCheckAll"
                :label="item._keyword"
                @change="handleParantChange($event, item)"
              >{{ item.name }}</el-checkbox>
            </div>
            <div v-if="item.child" class="select-item-child">
              <template v-for="(childItem) in item.child">
                <el-checkbox
                  v-if="!childItem.with && !childItem.hide"
                  :key="childItem.key"
                  :label="childItem.key"
                  @change="handleCheckedItemChange($event, item)"
                >{{ childItem.label }}</el-checkbox>
              </template>
              <div class="select-item-dash-container">
                <template v-for="(childItem) in item.child">
                  <i v-if="childItem.with" :key="childItem.key + 'dash'" class="dash"/>
                  <div v-if="childItem.with" :key="childItem.key" class="select-item-dash-child">
                    <el-checkbox
                      :label="childItem.key"
                      @change="handleCheckedItemChange($event, item)"
                    >{{ childItem.label }}</el-checkbox>
                  </div>
                </template>
              </div>
            </div>
          </div>
        </el-checkbox-group>
      </el-scrollbar>
    </div>
    <div class="btn-container" style="margin-top: 22px;display:flex;justify-content:center;">
      <!-- 导出按钮 -->
      <export-button
        ref="exportButton"
        :query-data="exportParams"
        :export-api="exportApi"
        :export-name="'资源列表'"
        http-method="post"
        is-diy
        is-before-export
        @beforeExport="beforeExport"
        @onComplate="completeExport"
      >
        <el-button type="primary" size="small" style="height:32px;">确定</el-button>
      </export-button>
      <el-button size="small" style="margin-left:15px;" class="btn cancel-btn-style" type="default" plain @click="handleClose">取消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { mapState } from 'vuex';
import { ExportExcelData } from '@/views/medium/mixin/mediumData';
import MaskContainer from './MaskContainer';
import ExportButton from '@/components/ExportButton';
import { isMediumNormal } from '@/utils/permission';
import Title from '@/components/Title';

export default {
  components: { MaskContainer, ExportButton, Title },
  props: {
    activeTabs: {
      type: String,
      default: '1'
    },
    searchKeyword: {
      type: String,
      default: ''
    },
    // 平台 tab
    tabs: {
      type: Array,
      default: null
    }
  },
  data() {
    return {
      dialogFormVisible: false,
      ExportExcelData,
      exportLoading: false,
      isIndeterminate: false,
      checkAll: false,
      commonData: [],
      selectKeyword: [],
      exportParams: {},
      exportApi: '/admin/medium/export'
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    })
  },
  created() {
  },
  methods: {
    tabMaskShow(params) {
      const exportParams = _.cloneDeep(params);
      this.exportParams = exportParams;
      this.exportLoading = false;
      this.handleData();
      this.dialogFormVisible = true;
    },
    beforeExport() {
      const mainKey = ['baseInfo', 'priceInfo', 'currencyPriceInfo', 'contactInfo', 'invoiceInfo', 'dataInfo', 'publishedPrice', 'costInfo', 'liaisonInfo'];
      // 去除主键
      const checkParams = _.without(this.selectKeyword, ...mainKey);
      // 判断字段不为空
      const params = this.exportParams;
      if (checkParams.length <= 0) {
        this.$message({
          type: 'error',
          message: '请至少选择一个字段'
        });
        return;
      }
      const ziduan = checkParams.join(',');
      params.ziduan = ziduan;
      params.searchKeyword = this.searchKeyword;
      this.exportLoading = true;
      this.$refs.exportButton.btnExport(params);
    },
    completeExport() {
      this.exportLoading = false;
      this.handleClose();
    },
    handleCheckAllChange(val) {
      // 如果全选则把所有key加入进 ths.selectKeyword
      // 第一步：取出所有key
      const commonData = this.commonData;
      const select = [];

      commonData.forEach(item => {
        item.childIsIndeterminate = false;
        if (val) {
          // 如果是全不选，则没有必要遍历取出key，优化速度
          select.push(item._keyword);
          item.child.forEach(childItem => {
            select.push(childItem.key);
          });
        }
      });
      // 第二步：去重并赋值，并更改状态
      this.selectKeyword = val ? _.uniq(select) : [];
      this.checkAll = val;
      this.isIndeterminate = false;
    },
    handleParantChange(val, item) {
      // 取出当前 item 所有 key
      const select = [];
      select.push(item._keyword);
      item.child.forEach(childItem => {
        if (!childItem.hide) select.push(childItem.key);
      });
      // 初始化 childIsIndeterminate
      item.childIsIndeterminate = false;
      // 判断是选中还是取消选中，如果选中则说明当前 item 全部选中，否则全部取消
      if (val) {
        this.selectKeyword.push(item._keyword);
        item.child.forEach(childItem => {
          this.selectKeyword.push(childItem.key);
        });
      } else {
        // 从 this.selectKeyword 删除当前 item 所有 key
        this.selectKeyword = this.selectKeyword.filter(filterSelect => {
          return !select.includes(filterSelect);
        });
      }
      this.freshSelect();
    },
    handleCheckedItemChange(value, item) {
      // 取出当前 item 所有 key
      const select = [];
      item.child.forEach(childItem => {
        select.push(childItem.key);
      });
      // selectChild 当前item，被选中的个数
      const selectChild = this.selectKeyword.filter(i => {
        return select.includes(i);
      });
      const totalLength = select.length;
      const checkedCount = selectChild.length;
      // 当前item是否被全选，不是则删除父节点的_keyword，让=使其取消勾选
      const childCheckAll = checkedCount === totalLength;
      if (childCheckAll) {
        this.selectKeyword.push(item._keyword);
      } else if (this.selectKeyword.indexOf(item._keyword) >= 0) {
        this.selectKeyword.splice(this.selectKeyword.indexOf(item._keyword), 1);
      }
      item.childIsIndeterminate = checkedCount > 0 && checkedCount < totalLength;
      this.freshSelect();
    },
    freshSelect() {
      // 去重
      this.selectKeyword = _.uniq(this.selectKeyword);
      // 判断全选的状态
      let totalLength = this.commonData.length;
      const checkedCount = this.selectKeyword.length;
      this.commonData.forEach(item => {
        const childItemLength = item.child.length;
        totalLength += childItemLength;
      });
      this.checkAll = checkedCount === totalLength;
      this.isIndeterminate = checkedCount > 0 && checkedCount < totalLength;
    },
    // 处理字段数据
    handleData() {
      const isMedium = isMediumNormal();
      const commonData = _.cloneDeep(this.ExportExcelData.common);
      let platform = '';
      for (let i = 0; i < this.tabs.length; i++) {
        const item = this.tabs[i];
        if (item.key === this.activeTabs) {
          platform = item.ziduan;
          break;
        }
      }
      const platformData = this.ExportExcelData[platform];
      // 结合
      for (let j = 0; j < commonData.length; j++) {
        const commonItem = commonData[j];
        for (let f = 0; f < platformData.length; f++) {
          const platformItem = platformData[f];
          if (commonItem._keyword === platformItem._keyword) {
            commonItem.child = commonItem.child.concat(platformItem.child);
          }
        }
      }
      // 追加
      platformData.forEach(item => {
        if (['publishedPrice', 'costInfo'].includes(item._keyword)) {
          commonData.push(item);
        }
      });
      if (!isMedium) {
        for (let i = 0; i < commonData.length; i++) {
          if (commonData[i]._keyword === 'contactInfo') {
            commonData[i].child = _.filter(commonData[i].child, function(o) { return o.key !== 'businessContact'; });
            break;
          }
        }
      }
      this.commonData = commonData;
      this.handleCheckAllChange(true);
    },
    handleClose() {
      this.dialogFormVisible = false;
    }
  }
};
</script>
<style scoped lang="scss">
.scroll-container {
  width: 100%;
  height: 100%;
}
.export-excel-mask-select-box {
  height: 364px;
  overflow: hidden;
  border-bottom: 1px solid #eee;
  margin-top:24px;
  border-top: 1px solid #eee;
  border-radius: 4px;
  .select-item {
    border-top: 1px solid #eee;
    border-left: 1px solid #eee;
    border-right: 1px solid #eee;
    &:first-child{
      border-top: none;
    }
    .select-item-common {
      height: 40px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #eee;
    }
    .select-item-parent {
      background-color: #fafafa;
      // border: solid 1px #eeeeee;
      padding: 0 11px;
    }

    .select-item-child {
      padding: 10px 14px 10px 34px;
      background-color: #ffffff;
      .select-item-dash-container {
        display: flex;
        flex-wrap: wrap;
        position: relative;
        .dash {
          display: none;
          &:first-child {
              // position: absolute;
              display: block;
              top: 0;
              left: 0;
              width: 100%;
              height: 1px;
              padding-top: 5px;
              margin-top: 5px;
              border-top: 1px dashed #eee;
          }
        }
        .select-item-dash-child {
          display: flex;
          flex-wrap: wrap;
          margin-right: 30px;

        }
      }
    }
  }
}
.check-grounp-style {
  &::v-deep {
    .el-checkbox__label {
      line-height: 24px;
      font-size: 13px;
      font-weight: normal;
    }
  }
}
</style>
